package com.sh.rbac.core.encrypt.interceptor;

import com.sh.rbac.core.encrypt.encryptor.EncryptManager;
import com.sh.rbac.core.encrypt.properties.EncryptProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.resultset.ResultSetHandler;
import org.apache.ibatis.plugin.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.sql.Statement;
import java.util.List;
import java.util.Properties;

/**
 * mybatis 解密拦截器
 *
 * @author wb
 * @since 2025-10-24
 */

@Slf4j
@Component
@Intercepts({
        @Signature(type = ResultSetHandler.class, method = "handleResultSets", args = Statement.class)
})
public class MybatisDecryptInterceptor implements Interceptor {

    @Autowired
    private EncryptProperties encryptProperties;

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        Object result = invocation.proceed();
        if (result instanceof List<?> list) {
            for (Object item : list) {
                EncryptManager.processEncryption(item, encryptProperties, false);
            }
        } else {
            EncryptManager.processEncryption(result, encryptProperties, false);
        }

        return result;
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {
        // 不需要特殊处理
    }

}
